<?php

namespace other\zongan;


use app\model\MobileOrder;
use Carbon\Carbon;
use think\facade\Log;

class ZhongAn
{

    const OrderStatusPay = 2; //已付款
    const OrderStatusSuccess = 3; //充值成功
    const OrderStatusRefund = 4; //已退款


    const orderStatus = [
        self::OrderStatusPay => '正在充值中',
        self::OrderStatusSuccess => '充值成功',
        self::OrderStatusRefund => '充值失败，已退款',
    ];


    public $client;


    public function __construct($service = 'zhongan.dm.account.getUsrInfoByCode')
    {
        require_once __DIR__ . '/../../../packages/zhongAnBaoXian/common/ZhongAnApiClient.php';

        // TODO 指定环境 iTest:测试环境; uat:预发环境; prd:生产环境
        $_env = isProd() ? 'prd' : "iTest";
        Log::info('众安的环境：'.$_env);

        // TODO 开发者的appKey，由众安提供
        $_appKey = isProd() ? '1ecd727748d47944a8439cb3a00e1da4' : "68b9bc0f4ea32f73fed77129fd21f96b";
        Log::info('众安的秘钥：'.$_appKey);


        // TODO 开发者的私钥，由开发者通过openssl工具生成，不需要PKCS8转码
        $_privateKey = "-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCvO1zT1OyNAk+N
YXWBZHvnwG3wDuPAZFJ5lz/9u8/bMzLmVbVXy30y3aBQnW7I5D/8zFGQwgwR1Oa7
R2Huc2a06Sxk0rnUUd0mrIQ2lsmR6wUvl4nM6K6eHcR9+v8/g2rPKULF7g5ltHmJ
NQlpI4kW8muI6purmkSCs2yxgIRYA44IUWH7quZDxbJGjtsUu65hD1t2c3Id7StG
fGWYRCZzHlQZWAnvpxvOBRfCnD27GNvOflvy6CgQL8u9Olh72TNZzh1nXt4HZQWF
456HatWmCH+giY1EaBeg+fvC3MIE//5YfznEhxRAs6blBREgYSAk/cs5/GkxywCL
buS3P5yBAgMBAAECggEAOtYuy/2hU5NkDK+dmc2YgO8uurz1IeNNggAT/2kxWINv
YsGCezEbH5okuwyxZwikp4gfFwDgtpgKxPUp37ulz7a/LjdHKBA4tkSUvBO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uMGKj4uevt6fMP+SZ3zZovtx/g
tf95y/w23pLLv7VK4/BBeRMV
-----END RSA PRIVATE KEY-----";

        // TODO 指定服务名，由众安提供

        $_client = new \ZhongAnApiClient($_env, $_appKey, $_privateKey, $service);

        $this->client = $_client;


    }


    /**
     * 获取授权手机号
     * @param $code
     * @return array|mixed
     * @throws \Exception
     */
    public function getPhoneByCode($code)
    {
        // TODO 业务参数，字段信息参照接口文档
        $_params = array(
            "authCode" => $code,
        );
        $_response = $this->client->call($_params);

        Log::info($_response);

        return $_response['bizContent'] ?? [];

    }

    /**
     * 推送订单到众安
     * @param MobileOrder $mobileOrder
     */
    public function pushOrder(MobileOrder $mobileOrder, $status = self::OrderStatusPay)
    {

        Log::info('触发了众安推送订单事件0');

        if (!$mobileOrder) return false;
        Log::info('触发了众安推送订单事件1');

        if (empty($mobileOrder->agentChannel)) return false;
        Log::info('触发了众安推送订单事件2');
        if (!in_array($mobileOrder->agent_channel->name, [
            'zabx',
            'huafeidmj',
        ])) return false;
        Log::info('触发了众安推送订单事件3');
        $user = $mobileOrder->user;

        $ext_data = [];

        try {

            $ext_data = $mobileOrder->ext_data ? json_decode($mobileOrder->ext_data,true) : [];

        }catch (\Exception $exception){
            Log::info('触发了众安推送订单事件4');
        }



        if (strlen($user->openid) != 11) return false;
        Log::info('层层过滤到了 众安处理了');
        $_params = [
            'phone' => $user->openid,
            'bizOrigin' => !empty($ext_data['bizOrigin']) ? $ext_data['bizOrigin']:'',//非必须
            'channel' => '1',
            'orderItem' => new \stdClass(),//传个空对象即可
            'orderTotalAmount' => fen2yuan($mobileOrder->sale_price),
            'outOrderNo' => $mobileOrder->order_id,
            'orderStatus' => $status,
            'orderStatusName' => self::orderStatus[$status] ?? '未知',
            'orderItems' => [
                'goodsName' => '话费充值面额：' . fen2yuan($mobileOrder->amount),
                'quantity' => 1,
                'goodsPictureUrl' => 'https://huichong-plugin.oss-cn-hangzhou.aliyuncs.com/common/bf0479b3f736b058f8e1f6bc34cc6d3.png',
            ],
            'skuDetailDTO' => [
                'goods' => [
                    'goodsBusinessType' => [
                        'code' => 'angsi',
                        'name' => '虚拟充值',
                    ],
                    'payExpireTime' => 0,
                ]
            ],
            'operationTime' => Carbon::now()->format('Y-m-d H:i:s')

        ];

//        file_put_contents('test.json',json_encode($_params,JSON_UNESCAPED_UNICODE));exit;

        $_response = $this->client->call($_params);

        if (empty($_response['bizContent']['returnCode'])) {
            Log::error('推送众安保险信息失败' . json_encode($_response));
            return true;
        }

        if ($_response['bizContent']['returnCode'] == 200){
            $mobileOrder->remark = $mobileOrder->remark.'zastatus:'.$status;
            $mobileOrder->save();
        }else{
            $mobileOrder->remark = '众安状态'.$_response['bizContent']['returnCode'];
            $mobileOrder->save();
        }

        return $_response['bizContent'] ?? [];

    }


}